/**
 * 初始化会员树图
 */
define(function(){
    var ec=require('echarts');

   require('echarts/chart/tree');
   

    var myChart = ec.init(document.getElementById('inventory_vip'));
    var datalist = [];
    var showMonth = ["2015-12"];
    var option   = {
    	    title : {
    	        
    	    },
    	  tooltip : {
    	        trigger: 'item',
    	        formatter: tooltipFunc
    	    },

    	    toolbox: {
    	        show : true,
    	        orient:'vertical',
    	        y:'bottom',
    	        feature : {
    	            mark : {show: true},
    	            dataView : {show: true, readOnly: false},
    	            restore : {show: true},
    	            saveAsImage : {show: true}
    	        }
    	    },
    	    calculable : true,
    	    color:['#30e0e0'],
    	    series : [
    	        {
    	            symbol:'emptyRectangle',
    	            name:'树图',
    	            symbolSize:[40,20],
    	            type:'tree',
    	            orient: 'horizontal',  // vertical horizontal
    	            rootLocation: {x: '80',y: 'center'},// 根节点位置  {x: 100, y: 'center'}
    	            nodePadding: 15,
    	            layerPadding:180,
    	            itemStyle: {
    	                normal: {
    	                    label: {
    	                        show:true,
    	                        formatter: "{b}"      	                    
    	                    },
    	                    lineStyle: {
    	                        color: '#48b',
    	                        shadowColor: '#000',
    	                        shadowBlur: 3,
    	                        shadowOffsetX: 3,
    	                        shadowOffsetY: 5,
    	                        type: 'broken' // 'curve'|'broken'|'solid'|'dotted'|'dashed'

    	                    }
    	                },
    	                emphasis: {
    	                    label: {
    	                        show: true
    	                    }
    	                }
    	            },
    	            
    	            data: [
    	                {
    	                    name: '会员量',
    	                    value: "vip_num",
    	                    children: [
    	                        {
    	                            name: '新建',
    	                            value: "new_vip_num",
    	                            children: [
    	                                {
    	                                    name: '打包',
    	                                    value: "db_vip_num",
    	                                    children:[{
    	                                       name: '开通',
    	                                       value: "dbkt_vip_num",
    	                                    },
    	                                    {
    	                                      name: '未开通',
    	                                      value: "dbwkt_vip_num",
    	                                    }]
    	                                },
    	                                {
    	                                    name: '裸开',
    	                                    value: "lk_vip_num",
    	                                   children:[{
    	                                       name: '充值',
    	                                       value: "lkcz_vip_num",
    	                                    },
    	                                    {
    	                                      name: '无充值',
    	                                      value: "lkwcz_vip_num",
    	                                    }]
    	                                }
    	                            ]
    	                        },
    	                        {
    	                            name: '留存',
     	                            value: "keep_vip_num",
    	                            children: [{
    	                                name: '有充值',
    	                                value: "keepcz_vip_num",
    	                                children:[{
    	                                       name: '开通',
    	                                       value: "keepczkt_vip_num",
    	                                    },
    	                                    {
    	                                      name: '未开通',
    	                                      value: "keepczwkt_vip_num",
    	                                    }]
    	         
    	                            },
    	                            {
    	                                name: '无充值有消费',
    	                                value: "keepwczyxh_vip_num",
    	                              children:[{
    	                                       name: '有续充',
    	                                       value: "keepwczyxhxc_vip_num",
    	                                    },
    	                                    {
    	                                      name: '无续充',
    	                                      value: "keepwczyxhwxc_vip_num",
    	                                    }]
    	                            },
    	                           {
    	                                name: '非活跃',
    	                                value: "keepinactive_vip_num"
    	                            }]
    	                        }
    	                    ]
    	                }
    	            ]
    	        }
    	    ]
    	};

    	                    
    	                    
               
    

    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    
    var months = [];
    function show(eventType){
            
    	  //myChart.setOption(option1,true);
    	var businessName = $('#businessName').val();
        var cityName = $('#cityName').val();
    	var realDate = $('#time_input_vip').val();

    	myChart.showLoading({
             text: '正在努力的读取数据中...'
        });	
    	$.ajax({
            url: '/dashboard/homePage/ajax/vip_tree',
            type: 'post',
            async: true,
            data:{"businessName": businessName, "cityName":cityName,"realDate":realDate},
            dataType: 'json',
            success: function(data, textStatus) {       
              
            	successData = data;
            	months = data.months;
            	
            	if(data.datalist[0] == null){
            		  myChart.showLoading({
            	             text: '您好，该业务线数据暂无...'
            	        });	
            		  $('#vipTotalTable tr:gt(0)').remove();
            		  return;
            	  }
            	 // console.log(data);
                 //第一次加载
            	 if(realDate.length == 0){
	               	  var length = data.datalist.length;
	               	  datalist = data.datalist[length-1];
	                  myChart.setOption(option,true);
	          	      myChart.hideLoading();
	               	  setTableData(datalist);
                 }else{
                	  if(data.datalist.length==1){
                		  datalist = data.datalist[0]; 		  
                	  }else{
                		  datalist = data.datalist[1];
                	  }
	                  myChart.setOption(option,true);
	          	      myChart.hideLoading();
	               	  setTableData(datalist);
                 }
            	 
            	 showMonth = [datalist["real_date"]];
            	  
            },
            error : function() {
                myChart.hideLoading();
            }
        });
       
    }
    
   
    
    
    var treeMap = ["vip_num","new_vip_num","db_vip_num","dbkt_vip_num","dbwkt_vip_num","lk_vip_num","lkcz_vip_num","lkwcz_vip_num","keep_vip_num","keepcz_vip_num","keepczkt_vip_num","keepczwkt_vip_num","keepwczyxh_vip_num","keepwczyxhxc_vip_num","keepwczyxhwxc_vip_num","keepinactive_vip_num"];
    //设置表格信息
    function setTableData(data){
    	//console.log(data);
    	
    	var htmlRows = "<tr>";
    	for(var i=0;i<4;i++){  		
    		if(i==0){
    			htmlRows += '<td>人 数</td>';
    			$.each(treeMap,function(key,value){
    	        	var lines = data[value].split(",");
    	        	htmlRows += setRow(lines[0]);
    	        	
    	        });
    		}else if(i==1){
    			htmlRows += '<td>总充值（w）</td>';
    			$.each(treeMap,function(key,value){
    	        	var lines = data[value].split(",");
    	        	if(value == "lkwcz_vip_num"||value == "keepwczyxh_vip_num"||value == "keepwczyxhxc_vip_num"||value == "keepwczyxhwxc_vip_num"||value == "keepinactive_vip_num"){
    	        		htmlRows += "<td>~</td>";
    	        	}else{
    	        		htmlRows += setRow(strFormatNumber(lines[1]));    	        		
    	        	}
    	        });
    		}else if(i==2){
    			htmlRows += '<td>总消耗（w）</td>';
    			$.each(treeMap,function(key,value){
    	        	var lines = data[value].split(",");
    	        	if(value == "dbwkt_vip_num"||value == "keepczwkt_vip_num"||value == "keepinactive_vip_num"){
    	        		htmlRows += "<td>~</td>";
    	        	}else if(value == "lkwcz_vip_num" ||value == "keepwczyxh_vip_num" ||value == "keepwczyxhxc_vip_num" ||value == "keepwczyxhwxc_vip_num" ){
    	        		htmlRows += setRow(strFormatNumber(lines[1]));
    	        	}else{
    	        		htmlRows += setRow(strFormatNumber(lines[2]));    	        		
    	        	}
    	        });
    		}else{
    			htmlRows += '<td>总余额（w）</td>';
    			$.each(treeMap,function(key,value){
    	        	var lines = data[value].split(",");
    	        	if(value == "dbwkt_vip_num" ||value == "lkwcz_vip_num" ||value == "keepczwkt_vip_num" ||value == "keepwczyxhxc_vip_num" ||value == "keepwczyxh_vip_num"||value == "keepwczyxhwxc_vip_num"){
    	        		htmlRows += setRow(strFormatNumber(lines[2]));
    	        	}else if(value == "keepinactive_vip_num"){
    	        		htmlRows += setRow(strFormatNumber(lines[1]));
    	        	}else{
    	        		htmlRows += setRow(strFormatNumber(lines[3]));    	        		
    	        	}
    	        });
    		}
    		htmlRows += "</tr>";
    	}
    	
    
    	$('#vipTotalTable tr:gt(0)').remove();              
        $('#vipTotalTable').append(htmlRows);
    }
    
    function setRow(td){
    	var td = "<td>"+td+"</td>";
    	return td;
    }
    
   
    //计算月环比(计算参数，昨天的数据跟今天的数据)
    function ybh(data_yesday,data_today){
            var s=(((data_today/data_yesday)-1)*100).toFixed(2);
            if(s>0){
                day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
            }else{
                day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
            }       
    	   return day_td;
    }
    
    //提示框
    function  tooltipFunc(params, ticket, callback){
        var data = datalist[params.value];
        
        var index_data = 0;
        $.each(successData.datalist,function(index,obj){
        	if(datalist["real_date"]==obj["real_date"]){
        		index_data = index;
        		return false;
        	}
        });
       
        if(index_data>0){
        	//上个月的数据
        	var data_yesday = successData.datalist[index_data-1];
        	var lists_yesday = data_yesday[params.value].split(',');
        }
        var lists = data.split(',');
        var result = '<table class="table-center">';
        result += '<tr><td>'+datalist.real_date+'</td><td>'+params.name+'</td><td>月环比</td></tr>';
        var yhb_td = '<td>--</td>';
        for(var i=0;i<lists.length;i++){
        	if(i!=0){
        		lists[i] = strFormatNumber(lists[i]);
        		if(index_data != 0){
        			lists_yesday[i] = strFormatNumber(lists_yesday[i]);
        		}
        	}else{
        		if(index_data != 0){
        			yhb_td = ybh(lists_yesday[i],lists[i]);
        		}
        		result += '<tr><td>'+"人 &nbsp;数：</td><td>"+lists[i]+'</td>'+yhb_td+'</tr>';        		
        	}
        	if(lists.length == 2){
        		if(index_data != 0){
                    yhb_td = ybh(lists_yesday[1],lists[1]);
        		}
        		result += '<tr><td>'+"总余额（w）：</td><td>"+strFormatNumber(lists[1])+'</td>'+yhb_td+'</tr>';
        		break;
        	}else if(lists.length == 3){
                var yhb_td2 = yhb_td;
                if(index_data != 0){
                    yhb_td = ybh(lists_yesday[1],lists[1]);
                    yhb_td2 = ybh(lists_yesday[2],lists[2]);
                }
        		 //打包未开通
        		 if(params.value == "dbwkt_vip_num"||params.value == "keepczwkt_vip_num"){
        			 result += getIndexShow(lists,"总充值","总余额",yhb_td, yhb_td2);
        			 break;
        		 }else {
        			 //裸开无充值
        			 result += getIndexShow(lists,"总消耗","总余额",yhb_td, yhb_td2);
        			 break;
        		 }
        		 //
        		 
        	}else{       		
        		if(i==1){
        			if(index_data != 0){
            			yhb_td = ybh(lists_yesday[i],lists[i]);
            		}
            		result += '<tr><td>'+"总充值（w）：</td><td>"+lists[i]+'</td>'+yhb_td+'</tr>';       		
            	}else if(i==2){
            		if(index_data != 0){
            			yhb_td = ybh(lists_yesday[i],lists[i]);
            		}
            		result += '<tr><td>'+"总消耗（w）：</td><td>"+lists[i]+'</td>'+yhb_td+'</tr>';        		
            	}else if(i==3){
            		if(index_data != 0){
            			yhb_td = ybh(lists_yesday[i],lists[i]);
            		}
            		result += '<tr><td>'+"总余额（w）：</td><td>"+lists[i]+'</td>'+yhb_td+'</tr>';        		
            	}
        	}
        }
        result+='</table>';
        return result;
    }   

    //获取只有三项指标的表格显示
    function getIndexShow(lists,index1,index2,yhb, yhb_td2){
    	var result = '';  	
        result += '<tr><td>'+index1+"（w）：</td><td>"+strFormatNumber(lists[1])+'</td>'+yhb+'</tr>';       		    	
        result += '<tr><td>'+index2+"（w）：</td><td>"+strFormatNumber(lists[2])+'</td>'+yhb_td2+'</tr>';        		   	
    	return result;
    }

        
    //时间勾选框事件
    $('#time_checkbox_vip').change(function(e){
        var input=$('#time_input_vip');
        if(!input)return;
        if($(this).is(":checked")){
            input.removeAttr('disabled');
            input.attr('placeholder','点击选择查看的月份');                 
            setDatePicker_v1(EC,"month",input);
        }else{
            input.val('');
            input.attr('disabled','');
            input.attr('placeholder','点击选择查看的月份');               
        }
    });

    //时间选择事件
    $('#time_input_vip').datepicker().on('changeDate',function(e){
    	show(2)
    });
    
    //以万元为单位
    function strFormatNumber(strNumber){
    	var number = parseFloat(strNumber);
    	number = number/10000;
    	return number.toFixed(2);
    }
    
    function getShowDays(){
        return showMonth;
    }
    
    function getAllDays(){   	
        return months;
    }


 var EC={
        show:show,
        getShowDays:getShowDays,
        getAllDays:getAllDays,
        resize:function(){myChart.resize()} 
    };
    
    return EC;    
});
